# -*- coding: utf-8 -*-
# @Python：3.8
# @项目：happiness_order
# @文件：user_service.py
# @时间：2025/1/20 15:20
# @作者：yangzhang
# @desc:
from bcrypt import gensalt, hashpw, checkpw


class UserService:
    @classmethod
    def gene_salt(cls, rounds=5):
        """
        生成随机的salt,用于密码加密
        :param rounds:表示哈希算法的迭代次数，越大越安全，但会增加计算耗时
        :return:返回随机生成的salt
        """
        _salt = gensalt(rounds)
        return _salt

    @classmethod
    def gene_pwd(cls, passwd, salt):
        """
        对明文密码通过随机字符salt进行加密
        :param passwd: 明文密码
        :param salt: 随机字符串
        :return: 加密的密码
        """
        hashed_pwd = hashpw(passwd.encode('utf-8'), salt)
        return hashed_pwd.decode('utf-8')

    @classmethod
    def check_pwd(cls, pwd_to_check: str, hashed_pwd: str):
        """
        校验密码
        :param pwd_to_check:需要进行校验的密码
        :param hashed_pwd: 数据库中存储的加密后的hash密码
        :return:校验成功返回True,失败返回false
        """
        _byte_pwd = pwd_to_check.encode('utf-8')
        _byte_hashed_pwd = hashed_pwd.encode('utf-8')
        if checkpw(_byte_pwd,_byte_hashed_pwd):
            return True
        else:
            return False


if __name__ == '__main__':
    salt = UserService.gene_salt()
    print(salt, len(salt))
    pwd = 'Abc135++'
    hash_pwd = UserService.gene_pwd(pwd, salt)
    print(hash_pwd, len(hash_pwd))
    print(UserService.check_pwd('Abc135++', hash_pwd))
